<script setup>
  import PageLayout from '@/components/PageLayout.vue'
  import GridTemplate from '@/components/GridTemplate.vue'
  import InfoCard from '@/components/InfoCard.vue'
  import { addRoom, addSeat, getRoomList, updateRoom, addBookshelf } from '@/api'
  import { useRouter, useRoute } from 'vue-router'
  import { onMounted, ref, computed, useTemplateRef } from 'vue'
  import { useDynamicForm } from '@/hooks'
  import { ElMessage } from 'element-plus'
  import { ElMessageBox } from 'element-plus'

  const { openForm } = useDynamicForm()

  const router = useRouter()
  const roomList = ref([])
  const route = useRoute()
  const libraryId = Number(route.params.id)
  const roomData = ref({})
  const infoCardCollapse = ref(true)
  const grid = useTemplateRef('grid')
  const readonly = computed(() => roomData.value.roomStatus !== 2)

  const statusMap = ['关闭', '开放', '维修']
  const TypeMap = ['教室', '自习室']

  const showInfoData = computed(() => {
    if (infoCardCollapse.value) return { title: ['房间:', roomData.value.name] }
    return {
      title: ['房间:', roomData.value.name],
      content: [
        [
          ['Id', roomData.value.id],
          ['所属图书馆', roomData.value.libraryId],
        ],
        [
          ['房间类型', roomData.value.typeName],
          ['状态', roomData.value.statusName],
        ],
        [
          ['容量', roomData.value.capacity],
          ['设备配置', roomData.value.equipmentConfig],
          ['设施配置', roomData.value.facilityConfig],
        ],
      ],
    }
  })

  const showGridOptions = computed(() => {
    return roomData.value.map ?? {}
  })

  const onBack = () => {
    router.back()
  }

  const onOpenForm = () => {
    const options = {
      title: '新建房间',
      fields: [
        {
          label: '房间名称',
          key: 'name',
          type: 'input',
          required: true,
        },
        {
          label: '房间类型',
          key: 'roomType',
          type: 'select',
          options: TypeMap.map((item, idx) => ({ label: item, value: idx })),
          default: 0,
          required: true,
        },
      ],
      onConfirm: (data, { close, setLoading }) => {
        setLoading(true)
        const body = {
          ...data,
          libraryId,
        }
        addRoom(body)
          .then(() => {
            ElMessage.success('新建房间成功')
            handleGetRoomList()
            close()
          })
          .finally(() => {
            setLoading(false)
          })
      },
    }

    openForm(options)
  }

  const onClickRoom = room => {
    roomData.value = room
  }

  const onClickCollapse = () => {
    infoCardCollapse.value = !infoCardCollapse.value
  }

  const onSubmitGrid = () => {
    ElMessageBox.confirm('确定提交布局吗？提交后不可修改', '提示').then(() => {
      const options = {
        title: '更新房间布局',
        fields: [
          {
            label: '容量(人)',
            key: 'capacity',
            type: 'number',
            default: 20,
            min: 1,
            max: 100,
          },
          {
            label: '设备配置',
            key: 'equipmentConfig',
            type: 'input',
          },
          {
            label: '设施配置',
            key: 'facilityConfig',
          },
        ],
        onConfirm: async (data, { close, setLoading }) => {
          setLoading(true)
          const id = Number(roomData.value.id)

          const map = grid.value.getMap()

          // 如果是自习室，生成座位和书架ID
          if (roomData.value.roomType === 1) {
            let promise = [] // 所有请求
            let number = 100 // 座位号
            let bookshelfNumber = 0 // 书架号
            map.data.forEach((item, idx) => {
              if (item.type === 2) {
                const body = { number: ++number, studyRoomId: id }
                const p = addSeat(body).then(res => {
                  item.id = res.data
                  item.number = body.number
                })
                promise.push(p)
              } else if (item.type === 3) {
                const top = idx - map.width
                const left = idx - 1
                const isTop = !map.data[top] || map.data[top].type !== 3
                const isLeft = !map.data[left] || map.data[left].type !== 3
                // 左边和上边都不是书架，则生成书架
                if (isTop && isLeft) {
                  const body = { number: ++bookshelfNumber, roomId: id }
                  const p = addBookshelf(body).then(res => {
                    item.id = res.data
                    item.number = `A${body.number}`
                  })
                  promise.push(p)
                }
              }
            })

            map.data = map.data.filter(item => item.type !== 0)
            await Promise.all(promise)
          }

          const body = {
            id,
            ...data,
            capacity: Number(data.capacity),
            map: JSON.stringify(map),
          }

          updateRoom(body)
            .then(() => {
              ElMessage.success('更新房间布局成功')
              handleGetRoomList()
              close()
            })
            .finally(() => setLoading(false))
        },
      }

      openForm(options)
    })
  }

  const onClickGridItem = item => {
    console.log(item.id)
  }

  const handleGetRoomList = () => {
    return getRoomList({ libraryId }).then(res => {
      roomList.value = res.data.map(item => ({
        ...item,
        statusName: statusMap[item.roomStatus],
        typeName: TypeMap[item.roomType],
        map: item.map ? JSON.parse(item.map) : { height: 15, width: 20, data: [] },
      }))
    })
  }

  onMounted(() => {
    handleGetRoomList().then(() => {
      roomData.value = roomList.value[0]
    })
  })
</script>

<template>
  <page-layout>
    <template #header>
      <el-button @click="onBack">返回</el-button>
      <el-button @click="handleGetRoomList">刷新</el-button>
      <el-button type="success" @click="onOpenForm">新建房间</el-button>
    </template>

    <div class="wrapper">
      <div class="flex-col">
        <div class="title">房间列表</div>
        <div class="room-list flex-col">
          <el-button v-for="room in roomList" :key="room.id" class="room-item shadow" @click="onClickRoom(room)">
            <span class="room-content">
              <span>{{ room.name }}</span>
              <el-tag effect="dark">{{ room.typeName }}</el-tag>
              <el-tag type="warning" effect="dark" v-if="room.roomStatus === 2">{{ room.statusName }}</el-tag>
            </span>
          </el-button>
        </div>
      </div>
      <div class="flex-1 flex-col">
        <div class="card-wrapper">
          <info-card :data="showInfoData" />
          <el-button class="collapse-btn" @click="onClickCollapse">展开/收起</el-button>
        </div>
        <grid-template ref="grid" :readonly="readonly" :options="showGridOptions" @click-item="onClickGridItem">
          <el-button type="success" @click="onSubmitGrid">提交布局</el-button>
        </grid-template>
      </div>
    </div>
  </page-layout>
</template>

<style scoped>
  .wrapper {
    display: flex;
    height: 100%;
    gap: var(--padding-2);
  }

  .title {
    text-align: center;
    position: sticky;
    top: 0;
    font-size: 28px;
    color: var(--primary-500);
    padding-bottom: 20px;
  }

  .room-list {
    width: 300px;
    gap: 16px;
    height: 100%;
    overflow-y: auto;
  }

  .room-item {
    padding: 30px;
    margin-left: 0;
  }

  .room-content {
    width: 100px;
    font-size: 20px;
    font-weight: 600;
    color: var(--primary-500);
    display: flex;
    gap: 20px;
    justify-content: center;
  }

  .card-wrapper {
    position: relative;
  }

  .collapse-btn {
    position: absolute;
    bottom: 20px;
    right: 20px;
  }
</style>
